#region Using

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using Gizmox.WebGUI.Forms;
using System.IO;
using System.Xml;

#endregion

namespace TVC.Forms
{
    public partial class frmTransferIn : Form
    {
        public enum TransferType
        {
            Insert,
            Update,
            InsertUpdate
        }
        public TransferType Type = TransferType.InsertUpdate;
        readonly string _strType = "";
        string fileType = "";
        DialogResult DResult = DialogResult.Cancel;
        public frmTransferIn(string strType, MainForm form)
        {
            InitializeComponent();
            _strType = strType;
            MainForm = form;
        }
        public frmTransferIn(Gizmox.WebGUI.Common.Interfaces.IContext objContext)
            : base(objContext)
        {

        }
        public MainForm MainForm { get; set; }
        public frmTransferIn(MainForm form)
        {
            MainForm = form;
        }


        private void btnBrowse_Click(object sender, EventArgs e)
        {
            ofd.FileOk += delegate(object form, System.ComponentModel.CancelEventArgs args)
            {
                if (((OpenFileDialog)form).DialogResult == Gizmox.WebGUI.Forms.DialogResult.OK)
                {
                    txtFileName.Text = ofd.FileName;
                    fileType = Path.GetExtension(ofd.File.OriginalFileName);
                    btnPreview.Enabled = true;
                    btnGroup.Enabled = btnImport.Enabled = false;
                }
            };
            ofd.ShowDialog();
        }



        private void btnPreview_Click(object sender, EventArgs e)
        {
            string sErr = "";
            lblErr.Text = "";
            if (fileType == ".xls" || fileType == ".xlsx")
            {
                DataTable dt = MainForm.GetTableStruct(_strType);
                //if (dt.ExtendedProperties.ContainsKey("Caption"))
                //    dgvList.Text = dt.ExtendedProperties["Caption"].ToString();
                //else dgvList.Text = dt.TableName;
                dt = TVC.clsTransfer.PreviewExcelFile(dt, txtFileName.Text, "", _strType);


                sErr = MainForm.TVCFormatData(dt, sErr, _strType);
                dgvList.DataSource = dt;
            }
            else if (fileType == ".xml")
            {
                DataTable dt = MainForm.GetTableStruct(_strType);
                dt = LoadXml(dt, txtFileName.Text, _strType);
                sErr = MainForm.TVCFormatData(dt, sErr, _strType);
                dgvList.DataSource = dt;
            }
            TVC.clsTransfer trans = new clsTransfer(MainForm);
            trans.ValidateDGV(dgvList, errorProvider1);
            if (errorProvider1.GetError(dgvList) == "")
            {
                btnGroup.Enabled = true;
                btnPreview.Enabled = false;
            }
            else
            {
                lblErr.Text = errorProvider1.GetError(dgvList).Trim();
            }
        }

    

        private static DataTable LoadXml(DataTable dt, string p, string _strType)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(p);
            XmlElement doc = xml.DocumentElement;
            foreach (XmlElement ele in doc.ChildNodes)
            {
                if (ele.Name == _strType)
                {
                    DataRow row = dt.NewRow();
                    foreach (XmlElement att in ele.ChildNodes)
                    {
                        if (!dt.Columns.Contains(att.Name))
                            dt.Columns.Add(att.Name);
                        row[att.Name] = att.InnerText;
                    }
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string sErr = "";
            string sErrRow = "";
            if (ckbIns.Checked == false && ckbUp.Checked == false)
            {
                //MessageBox.Show("Please select a mode!");
                //return;
                for (int i = 0; i < dgvList.Rows.Count; i++)
                    if (dgvList.Rows[i].ErrorText == "")
                    {
                        sErrRow = BUS.CommonControl.TransferInData(((DataRowView)dgvList.Rows[i].DataBoundItem).Row, _strType, MainForm.PODInfo);
                        sErr += sErrRow;
                        if (sErrRow != "")
                        {
                            dgvList.Rows[i].ErrorText = sErrRow;
                        }
                    }
            }
            else if (ckbUp.Checked == true)
            {
                for (int i = 0; i < dgvList.Rows.Count; i++)
                    if (dgvList.Rows[i].ErrorText == "")
                    {
                        sErrRow = BUS.CommonControl.Update(((DataRowView)dgvList.Rows[i].DataBoundItem).Row, _strType, MainForm.PODInfo);
                        sErr += sErrRow;
                        if (sErrRow != "")
                        {
                            dgvList.Rows[i].ErrorText = sErrRow;
                        }
                    }
            }
            else
            {
                for (int i = 0; i < dgvList.Rows.Count; i++)
                    if (dgvList.Rows[i].ErrorText == "")
                    {
                        sErrRow = BUS.CommonControl.Insert(((DataRowView)dgvList.Rows[i].DataBoundItem).Row, _strType, MainForm.PODInfo);
                        sErr += sErrRow;
                        if (sErrRow != "")
                        {
                            dgvList.Rows[i].ErrorText = sErrRow;
                        }
                    }
            }
            if (sErr == "")
            {
                MessageBox.Show("Import data successfull!", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                DResult = DialogResult.OK;
                Close();
            }
            else
            {
                //MessageBox.Show(sErr, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                MessageBox.Show("Import data not successfull, please check!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
            }
            lblErr.Text = sErr;
            btnImport.Enabled = false;
            btnPreview.Enabled = false;
        }

        private void dgvList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            dgvList.Rows[e.RowIndex].ErrorText = e.ThrowException.ToString();
            dgvList.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
            lblErr.Text += String.Format("{0}\n", e.ThrowException);
            errorProvider1.SetError(dgvList, lblErr.Text);
        }

        private void btnGroup_Click(object sender, EventArgs e)
        {

            btnImport.Enabled = true;
            btnGroup.Enabled = false;
            if (dgvList.RowCount > 0)
            {
                DataSet dset = null;
                DataTable dt = dgvList.DataSource as DataTable;

                DataSetHelper dsHelper = new DataSetHelper(ref dset);
                string strField = "";
                string filter = "";
                string groupField = "";
                foreach (DataColumn col in dt.Columns)
                {
                    strField += "," + col.ColumnName;
                    groupField += "," + col.ColumnName;
                }
                strField = strField.Substring(1);
                groupField = groupField.Substring(1);

                DataTable dtgroup = dsHelper.SelectGroupByInto("Group", dt, strField, filter, groupField);
                dgvList.DataSource = dtgroup;
                lblErr.Text = String.Format("You have {0} records by Group", dtgroup.Rows.Count);
                btnImport.Enabled = dtgroup.Rows.Count > 0;

            }


        }

        private void dgvList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex != -1)
                if (dgvList.Rows[e.RowIndex].ErrorText != "")
                    lblErr.Text = dgvList.Rows[e.RowIndex].ErrorText;
        }

        private void lblErr_Click(object sender, EventArgs e)
        {
            MessageBox.Show(lblErr.Text);
        }

        private void frmTransferIn_Load(object sender, EventArgs e)
        {
            if (Type == TransferType.Insert)
                ckbUp.Enabled = false;
            else if (Type == TransferType.Update)
                ckbIns.Enabled = false;
        }

        private void frmTransferIn_FormClosed(object sender, FormClosedEventArgs e)
        {
            DialogResult = DResult;
        }
    }
}